import 'package:bxultimate/app/router/router_name.dart';
import 'package:bxultimate/data/request/home_request.dart';
import 'package:bxultimate/domain/home/search_hint.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'state.dart';

class HomeSearchController extends GetxController {
  final HomeSearchState state = HomeSearchState();

  TextEditingController? editingController;

  @override
  void onInit() {
    super.onInit();
    editingController = TextEditingController();

    editingController?.addListener(() async {
      state.searchText = editingController!.text;
      state.searchHintList =
          await HomeRequest.getSearchHintList(editingController!.text);
    });
    var arr = UtilSp.getString(AppConstant.searchHistory, defValue: "")!.split(",");
    // 过滤掉数字中位空的
    arr.removeWhere((element) => element.isEmpty);
    state.historySearchList =arr;

  }

  onSearch(String text) {
    if(!state.historySearchList.contains(text)){
      state.historySearchList.add(text);
    }
    print(state.historySearchList);
    UtilSp.putString(AppConstant.searchHistory, state.historySearchList.join(","));

    Get.toNamed(RouterName.homeSearchResult,arguments: text);
  }

  void toDetail(SearchHint searchHint) {
    if (searchHint.type == "zqgs" || searchHint.type == "article") {
      Get.toNamed(RouterName.articleDetail, arguments: searchHint.id);
    } else if (searchHint.type == "shop") {
      Get.toNamed(RouterName.shopActivityDetail, arguments: searchHint.id);
    }
  }
}
